#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>

#define PORT 8080  // 端口号
#define BACKLOG 10  // 最大连接数

// 简单的HTML页面
const std::string HTTP_RESPONSE = 
    "HTTP/1.1 200 OK\r\n"
    "Content-Type: text/html\r\n"
    "Connection: close\r\n"
    "\r\n"
    "<html><head><title>Hello World</title></head>"
    "<body><h1>Hello World from C++ HTTP Server</h1></body></html>";

// 处理客户端请求的函数
void* handle_client(void* client_socket_ptr) {
    int client_socket = *(int*)client_socket_ptr;
    char buffer[1024];

    // 读取请求
    int bytes_received = read(client_socket, buffer, sizeof(buffer) - 1);
    if (bytes_received > 0) {
        // 输出接收到的请求信息
        buffer[bytes_received] = '\0';
        std::cout << "Received request:\n" << buffer << std::endl;

        // 向客户端发送HTTP响应
        write(client_socket, HTTP_RESPONSE.c_str(), HTTP_RESPONSE.length());
    } else {
        std::cerr << "Failed to read request\n";
    }

    // 关闭连接
    close(client_socket);

    // 线程结束
    pthread_exit(NULL);
}

int main() {
    // 创建TCP socket
    int server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        perror("Socket creation failed");
        return 1;
    }

    // 配置服务器地址结构
    sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;  // 允许接受任何IP的连接
    server_addr.sin_port = htons(PORT);

    // 绑定socket到指定地址
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("Bind failed");
        close(server_socket);
        return 1;
    }

    // 监听连接
    if (listen(server_socket, BACKLOG) == -1) {
        perror("Listen failed");
        close(server_socket);
        return 1;
    }

    std::cout << "HTTP Server running on http://<your_ip>:" << PORT << std::endl;

    while (true) {
        // 接受客户端连接
        sockaddr_in client_addr;
        socklen_t client_len = sizeof(client_addr);
        int client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_len);
        if (client_socket == -1) {
            perror("Accept failed");
            continue;
        }

        // 创建线程处理客户端请求
        pthread_t thread_id;
        if (pthread_create(&thread_id, NULL, handle_client, (void*)&client_socket) != 0) {
            perror("Thread creation failed");
            close(client_socket);
        } else {
            // 分离线程，这样线程结束后会自动释放资源
            pthread_detach(thread_id);
        }
    }

    // 关闭服务器socket
    close(server_socket);
    return 0;
}
